﻿using NHibernate;
using PAP.Application.Core;
using PAP.Domain.Core.Entities;
using PAP.Domain.Core.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PAP.Infrastructure.DataAccess.NH.Domain.Repositories
{
    public abstract class RepositoryBase<TKey,TEntity> : IRepository<TKey,TEntity>
        where TEntity : Entity<TKey>
    {
        #region "Fields"
        private readonly NHUnitOfWork _unitOfWork;
        #endregion

        #region "Constructors"
        public RepositoryBase(IUnitOfWork unitOfWork)
        {
            this._unitOfWork = unitOfWork as NHUnitOfWork;
        }
        #endregion

        #region "Properties"
        protected virtual ISession Session
        {
            get { return this._unitOfWork.Context; }
        }
        #endregion

        #region "Methods"
        public virtual TEntity Load(TKey id)
        {
            return Session.Load<TEntity>(id);
        }

        public virtual void Add(TEntity entity)
        {
            Session.Save(entity);
        }

        public virtual void Add(IEnumerable<TEntity> entities)
        {
            foreach (var entity in entities)
            {
                Add(entity);
            }
        }

        public virtual void Delete(TEntity entity)
        {
            Session.Delete(entity);
        }

        public virtual void Delete(IEnumerable<TEntity> entities)
        {
            foreach (var entity in entities)
            {
                Delete(entity);
            }
        }

        public virtual void Update(TEntity entity)
        {
            Session.Update(entity);
        }

        public virtual void Update(IEnumerable<TEntity> entities)
        {
            foreach (var entity in entities)
            {
                Update(entity);
            }
        }
        #endregion
    }
}
